import type { NavigationGuardNext, RouteLocationNormalized, RouteRecordRaw } from "vue-router";
import { createRouter, createWebHashHistory } from "vue-router";
import NProgress from "@/utils/nprogress";
import { constantRoutes } from "./modules/router";
import type { App } from "vue";
/**
 * 创建路由
 */
const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes as RouteRecordRaw[],
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

// 白名单路由
const whiteList = ["/homePage"];

router.beforeEach(
  async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    NProgress.start();
    // 路由守卫操作
    if (whiteList.includes(to.path)) {
      next();
    } else {
      // 不在白名单，重定向到登录页
      NProgress.done();
    }
  }
);

// 后置守卫，保证每次路由跳转结束时关闭进度条
router.afterEach(() => {
  NProgress.done();
});

// 全局注册 router
export function setupRouter(app: App<Element>) {
  app.use(router);
}

export default router;
